<script setup>
import { ref } from 'vue'
import moment from 'moment';
import { 
  leavePageService, 
  updateLeaveStatusService 
} from "@/api/leave";
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索条件
const searchForm = ref({
  employeeName: '',
  leaveType: '',
  status: '',
  timeRange:'',
})

// 分页数据
// const pagination = ref({
//   page: 1,
//   pageSize: 10,
//   total: 0
// })
//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

 //当每页条数发生了变化，调用此函数
 const onSizeChange = (size) => {
  pageSize.value = size
  employeeList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  employeeList()
}

// 请假数据
//员工数据模型模型
const leaveData = ref([{
  id: '',
  userName: '',
  leaveType: '',
  startTime: '',
  endTime: '',
  duration:'',
  reason:'',
  status:'',
}])


// 请假类型选项
const leaveTypeOptions = [
  { label: '病假', value: 0 },
  { label: '事假', value: 1 },
  { label: '年假', value: 2 },
  { label: '调休', value: 3 }
]

// 状态选项
const statusOptions = [
  { label: '待审批', value: 0 },
  { label: '已通过', value: 1 },
  { label: '已拒绝', value: 2 },
  {  label: '已撤销', value: 3 }
]

// 获取请假列表
const LeaveList = async () => {
  const [startTime, endTime] = searchForm.value.timeRange || [null, null];
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    employeeName: searchForm.value.employeeName,
    leaveType: searchForm.value.leaveType,
    status: searchForm.value.status,
    startTime: startTime 
      ? moment(startTime).add(1, 'day').utc().startOf('day').format()  // 当日 00:00:00 的 UTC 时间
      : '',
    endTime: endTime 
      ? moment(endTime).add(1, 'day').utc().endOf('day').format()  // 次日 00:00:00 的 UTC 时间
      : ''
  }
  const result = await leavePageService(params);
  //渲染视图
  total.value = result.data.total
  leaveData.value = result.data.records.map(leave => ({
    ...leave,
  }))
  
}

// 处理审批
const handleApprove = (row,status) => {
  ElMessageBox.confirm(
      `你确认要${status === 1 ? '通过' : '拒绝'}该用户吗？`,
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 确认后弹出输入框填写审批意见
    return ElMessageBox.prompt(
      `请输入${status === 1 ? '通过' : '拒绝'}原因：`,
      '审批意见',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入审批意见'
      }
    );
  }
  )
  .then(
    async ({ value: approveComment }) => {
      row.approveComment = approveComment;
     const params = {
      id: row.id,
      status,
      approveComment: row.approveComment
    }
      const result = await updateLeaveStatusService(params)
      ElMessage({
      showClose: true,
      message: result.msg ? result.msg :  `${status === 1 ? '通过' : '拒绝'}成功`,
      type: 'success',
    })
  LeaveList()
  }
  )
 
}

// 初始化加载
LeaveList()
</script>

<template>
  <el-card class="page-container">
    <template #header>
      请假管理
    </template>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline>
      <el-form-item label="员工姓名" >
        <el-input v-model="searchForm.employeeName" placeholder="请输入姓名" style="width: 112px;" />
      </el-form-item>

      <el-form-item label="请假类型" >
        <el-select v-model="searchForm.leaveType" clearable style="width: 102px;">
          <el-option 
            v-for="item in leaveTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="searchForm.status" clearable style="width: 102px;">
          <el-option 
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="LeaveList">搜索</el-button>
        <el-button @click="searchForm = {}">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="leaveData" stripe>
      <el-table-column prop="userName" label="员工姓名" width="120"/>
      <el-table-column prop="leaveType" label="类型" width="100">
        <template #default="{row}">
          {{ leaveTypeOptions.find(o => o.value === row.leaveType)?.label }}
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180"/>
      <el-table-column prop="endTime" label="结束时间" width="180"/>
      <el-table-column prop="duration" label="时长（天）" width="100"/>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : row.status === 2 ? 'danger' : 'warning'">
            {{ statusOptions.find(o => o.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="事由" show-overflow-tooltip/>
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button 
            v-if="row.status === 0"
            type="success" 
            size="small"
            @click="handleApprove(row, 1)"
          >
            通过
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="danger"
            size="small"
            @click="handleApprove(row, 2)"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>